import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/components/login.vue'
import Home from '@/components/home.vue'

Vue.use(VueRouter)

const router = new VueRouter({
  routes:[
    { path:"/" , redirect:"/login" },
    { path:"/login" , name:"登录" , component:Login },
    { path:"/home", name:"首页" , component:Home }
  ]
})

//挂在路由导航守卫 beforeEach()
/*
  @arguments  to 将要访问的路径
  @arguments  from 代表从哪个路径跳转而来
  @arguments  next 是一个函数，表示放行
              next() 放行 
              next('/login') 强制跳转
*/
router.beforeEach((to, from, next) => {
  console.log(to)
  if(to.path === '/login' || to.path === '/register') return next();
  // 获取token
  const tokenStr = window.sessionStorage.getItem('token');
  if(!tokenStr)return next('/login');
  next()
})

export default router;